<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>预约管理 - 宠物医院管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/css/style.css" rel="stylesheet">
    <style>
        .status-badge {
            font-size: 0.8rem;
            padding: 4px 8px;
        }
        .search-form {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .action-buttons {
            margin-bottom: 20px;
        }
        .appointment-time {
            font-weight: 600;
            color: #495057;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 p-0">
                <%@ include file="../common/admin-sidebar.jsp" %>
            </div>
            
            <!-- 主内容区 -->
            <div class="col-md-10">
                <div class="main-content p-4">
                    <!-- 页面标题 -->
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-calendar-check me-2"></i>预约管理</h2>
                        <nav aria-label="breadcrumb">
                            <ol class="breadcrumb">
                                <li class="breadcrumb-item"><a href="${pageContext.request.contextPath}/pages/admin/dashboard.jsp">首页</a></li>
                                <li class="breadcrumb-item active">预约管理</li>
                            </ol>
                        </nav>
                    </div>

                    <!-- 提示信息 -->
                    <c:if test="${not empty param.success}">
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle me-2"></i>${param.success}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    </c:if>
                    <c:if test="${not empty param.error}">
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-circle me-2"></i>${param.error}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    </c:if>

                    <!-- 搜索表单 -->
                    <div class="search-form">
                        <form method="get" action="${pageContext.request.contextPath}/appointment/list">
                            <input type="hidden" name="action" value="list">
                            <div class="row g-3">
                                <div class="col-md-3">
                                    <label class="form-label">宠物姓名</label>
                                    <input type="text" class="form-control" name="petName" value="${petName}" placeholder="请输入宠物姓名">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">服务类型</label>
                                    <select class="form-select" name="serviceType">
                                        <option value="">全部类型</option>
                                        <c:forEach var="type" items="${serviceTypes}">
                                            <option value="${type}" ${serviceType == type ? 'selected' : ''}>${type}</option>
                                        </c:forEach>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">预约状态</label>
                                    <select class="form-select" name="status">
                                        <option value="">全部状态</option>
                                        <option value="pending" ${status == 'pending' ? 'selected' : ''}>待确认</option>
                                        <option value="confirmed" ${status == 'confirmed' ? 'selected' : ''}>已确认</option>
                                        <option value="completed" ${status == 'completed' ? 'selected' : ''}>已完成</option>
                                        <option value="cancelled" ${status == 'cancelled' ? 'selected' : ''}>已取消</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">预约日期</label>
                                    <input type="date" class="form-control" name="appointmentDate" value="${appointmentDate}">
                                </div>
                            </div>
                            <div class="row mt-3">
                                <div class="col-12">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-search me-2"></i>搜索
                                    </button>
                                    <a href="${pageContext.request.contextPath}/appointment/list" class="btn btn-outline-secondary ms-2">
                                        <i class="fas fa-undo me-2"></i>重置
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="action-buttons">
                        <a href="${pageContext.request.contextPath}/pages/admin/appointment-add.jsp" class="btn btn-success">
                            <i class="fas fa-plus me-2"></i>添加预约
                        </a>
                        <button type="button" class="btn btn-danger" onclick="batchDelete()">
                            <i class="fas fa-trash me-2"></i>批量删除
                        </button>
                        <a href="${pageContext.request.contextPath}/export/appointments" class="btn btn-warning">
                            <i class="fas fa-download me-2"></i>导出数据
                        </a>
                    </div>

                    <!-- 预约列表 -->
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-list me-2"></i>预约列表
                                <span class="badge bg-primary ms-2">${pageResult.totalCount}</span>
                            </h5>
                        </div>
                        <div class="card-body p-0">
                            <c:choose>
                                <c:when test="${empty pageResult.data}">
                                    <div class="text-center py-5">
                                        <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                                        <p class="text-muted">暂无预约数据</p>
                                    </div>
                                </c:when>
                                <c:otherwise>
                                    <div class="table-responsive">
                                        <table class="table table-hover mb-0">
                                            <thead>
                                                <tr>
                                                    <th width="50">
                                                        <input type="checkbox" id="selectAll" class="form-check-input">
                                                    </th>
                                                    <th>预约信息</th>
                                                    <th>宠物信息</th>
                                                    <th>主人</th>
                                                    <th>服务类型</th>
                                                    <th>预约时间</th>
                                                    <th>医生</th>
                                                    <th>状态</th>
                                                    <th width="200">操作</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <c:forEach var="appointment" items="${pageResult.data}">
                                                    <tr>
                                                        <td>
                                                            <input type="checkbox" name="appointmentIds" value="${appointment.appointmentId}" class="form-check-input">
                                                        </td>
                                                        <td>
                                                            <div>
                                                                <strong>#${appointment.appointmentId}</strong>
                                                            </div>
                                                            <small class="text-muted">
                                                                <fmt:formatDate value="${appointment.createTime}" pattern="yyyy-MM-dd HH:mm"/>
                                                            </small>
                                                        </td>
                                                        <td>
                                                            <c:if test="${not empty appointment.pet}">
                                                                <div><strong>${appointment.pet.petName}</strong></div>
                                                                <small class="text-muted">${appointment.pet.petType}</small>
                                                            </c:if>
                                                        </td>
                                                        <td>
                                                            <c:if test="${not empty appointment.owner}">
                                                                ${appointment.owner.realName}
                                                            </c:if>
                                                        </td>
                                                        <td>${appointment.serviceType}</td>
                                                        <td>
                                                            <div class="appointment-time">
                                                                <fmt:formatDate value="${appointment.appointmentDate}" pattern="yyyy-MM-dd"/>
                                                            </div>
                                                            <small class="text-muted">
                                                                <fmt:formatDate value="${appointment.appointmentTime}" pattern="HH:mm"/>
                                                            </small>
                                                        </td>
                                                        <td>
                                                            <c:choose>
                                                                <c:when test="${not empty appointment.doctorName}">
                                                                    ${appointment.doctorName}
                                                                </c:when>
                                                                <c:otherwise>
                                                                    <span class="text-muted">未分配</span>
                                                                </c:otherwise>
                                                            </c:choose>
                                                        </td>
                                                        <td>
                                                            <span class="badge status-badge 
                                                                ${appointment.status == 'pending' ? 'bg-warning' : 
                                                                  appointment.status == 'confirmed' ? 'bg-info' : 
                                                                  appointment.status == 'completed' ? 'bg-success' : 'bg-secondary'}">
                                                                ${appointment.statusDisplay}
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group btn-group-sm">
                                                                <a href="${pageContext.request.contextPath}/appointment/view?action=view&id=${appointment.appointmentId}" 
                                                                   class="btn btn-outline-info" title="查看">
                                                                    <i class="fas fa-eye"></i>
                                                                </a>
                                                                <c:if test="${appointment.status == 'pending'}">
                                                                    <button type="button" class="btn btn-outline-success" 
                                                                            onclick="confirmAppointment(${appointment.appointmentId})" title="确认">
                                                                        <i class="fas fa-check"></i>
                                                                    </button>
                                                                </c:if>
                                                                <c:if test="${appointment.status == 'confirmed'}">
                                                                    <button type="button" class="btn btn-outline-primary" 
                                                                            onclick="completeAppointment(${appointment.appointmentId})" title="完成">
                                                                        <i class="fas fa-check-double"></i>
                                                                    </button>
                                                                </c:if>
                                                                <a href="${pageContext.request.contextPath}/appointment/edit?action=edit&id=${appointment.appointmentId}" 
                                                                   class="btn btn-outline-primary" title="编辑">
                                                                    <i class="fas fa-edit"></i>
                                                                </a>
                                                                <button type="button" class="btn btn-outline-danger" 
                                                                        onclick="deleteAppointment(${appointment.appointmentId})" title="删除">
                                                                    <i class="fas fa-trash"></i>
                                                                </button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                </c:forEach>
                                            </tbody>
                                        </table>
                                    </div>
                                </c:otherwise>
                            </c:choose>
                        </div>
                    </div>

                    <!-- 分页 -->
                    <c:if test="${pageResult.totalPages > 1}">
                        <nav class="mt-4">
                            <ul class="pagination justify-content-center">
                                <li class="page-item ${pageResult.hasPrevious ? '' : 'disabled'}">
                                    <a class="page-link" href="?action=list&page=${pageResult.currentPage - 1}&petName=${petName}&serviceType=${serviceType}&status=${status}&appointmentDate=${appointmentDate}">
                                        <i class="fas fa-chevron-left"></i>
                                    </a>
                                </li>
                                
                                <c:forEach begin="1" end="${pageResult.totalPages}" var="i">
                                    <c:if test="${i <= 5 || i > pageResult.totalPages - 5 || (i >= pageResult.currentPage - 2 && i <= pageResult.currentPage + 2)}">
                                        <li class="page-item ${i == pageResult.currentPage ? 'active' : ''}">
                                            <a class="page-link" href="?action=list&page=${i}&petName=${petName}&serviceType=${serviceType}&status=${status}&appointmentDate=${appointmentDate}">${i}</a>
                                        </li>
                                    </c:if>
                                </c:forEach>
                                
                                <li class="page-item ${pageResult.hasNext ? '' : 'disabled'}">
                                    <a class="page-link" href="?action=list&page=${pageResult.currentPage + 1}&petName=${petName}&serviceType=${serviceType}&status=${status}&appointmentDate=${appointmentDate}">
                                        <i class="fas fa-chevron-right"></i>
                                    </a>
                                </li>
                            </ul>
                            <div class="text-center text-muted">
                                ${pageResult.pageInfo}
                            </div>
                        </nav>
                    </c:if>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全选/取消全选
        document.getElementById('selectAll').addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('input[name="appointmentIds"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });

        // 确认预约
        function confirmAppointment(appointmentId) {
            if (confirm('确定要确认这个预约吗？')) {
                fetch('${pageContext.request.contextPath}/appointment/confirm', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'action=confirm&id=' + appointmentId
                })
                .then(response => response.text())
                .then(data => {
                    if (data === 'success') {
                        location.reload();
                    } else {
                        alert('确认失败');
                    }
                });
            }
        }

        // 完成预约
        function completeAppointment(appointmentId) {
            if (confirm('确定要标记这个预约为已完成吗？')) {
                fetch('${pageContext.request.contextPath}/appointment/complete', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'action=complete&id=' + appointmentId
                })
                .then(response => response.text())
                .then(data => {
                    if (data === 'success') {
                        location.reload();
                    } else {
                        alert('操作失败');
                    }
                });
            }
        }

        // 删除预约
        function deleteAppointment(appointmentId) {
            if (confirm('确定要删除这个预约吗？此操作不可恢复！')) {
                window.location.href = '${pageContext.request.contextPath}/appointment/delete?action=delete&id=' + appointmentId;
            }
        }

        // 批量删除
        function batchDelete() {
            const checkboxes = document.querySelectorAll('input[name="appointmentIds"]:checked');
            if (checkboxes.length === 0) {
                alert('请选择要删除的预约');
                return;
            }
            
            if (confirm('确定要删除选中的 ' + checkboxes.length + ' 个预约吗？此操作不可恢复！')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '${pageContext.request.contextPath}/appointment/batchDelete';
                
                const actionInput = document.createElement('input');
                actionInput.type = 'hidden';
                actionInput.name = 'action';
                actionInput.value = 'batchDelete';
                form.appendChild(actionInput);
                
                checkboxes.forEach(checkbox => {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = 'appointmentIds';
                    input.value = checkbox.value;
                    form.appendChild(input);
                });
                
                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>
</body>
</html>
